import Icon, { ClearOutlined } from '@ant-design/icons';
import { FloatButton } from 'antd';
import type { LngLat } from 'mapbox-gl';
import { useEffect, useMemo, useRef, useState } from 'react';
import type { Mapless } from '@/components/MapView';
import DraggableMarker from '@/components/MapView/components/DraggableMarker/Index';
import { PositionMarker } from '@/components/MapView/Mapless/core/position.mkr';
import getPositionSvg from '../../icons/getPosition.svg?react';
import pointSvg from '../../icons/point.svg?react';
import type { IconType } from '../index.d';
import styles from '../index.module.less';

const PositionMkr: React.FC<{
  mapless: Mapless | undefined;
  reset: number;
}> = (props) => {
  const { mapless, reset } = props;

  const pmkrRef = useRef<PositionMarker>(undefined);

  const [mkrs, setMkrs] = useState<LngLat[]>([]);

  const [mode, setMode] = useState('');

  useEffect(() => {
    if (mapless?.map) {
      pmkrRef.current = new PositionMarker(mapless.map);
    }
  }, [mapless]);

  useEffect(() => {
    if (reset > 0) {
      setMode('');
      pmkrRef.current?.stop();
    }
  }, [reset]);

  const icons: IconType = useMemo(
    () => ({
      point: <Icon component={pointSvg} />,
      getPosition: <Icon component={getPositionSvg} />,
      getPosition_s: (
        <Icon
          component={getPositionSvg}
          style={{ color: 'var(--theme-color-primary)' }}
        />
      ),
      clear: <ClearOutlined />,
    }),
    [],
  );

  const onModeClick = async (mode: string) => {
    if (mode === 'clear') {
      setMkrs([]);
      return;
    }
    if (mode === 'stop') {
      setMode('');
      pmkrRef.current?.stop();
    }
    if (mode === 'start') {
      setMode('getPosition');
      if (pmkrRef.current) {
        mapless?.interactionLayers(false);
        const [coords, error] = await pmkrRef.current.startPointPickingAsync();
        if (coords && !error) {
          setMkrs((prev) => [...prev, coords]);
          console.log(coords);
        }
        mapless?.interactionLayers(true);
      }
      setMode('');
    }
  };

  return (
    <>
      <FloatButton.Group
        trigger="hover"
        shape="square"
        placement="right"
        className={styles.drawtool}
        tooltip={{
          title: '标记',
          placement: 'left',
          rootClassName: styles.tooltip,
        }}
        icon={icons[mode ? `${mode}_s` : 'getPosition']}
        onClick={() => onModeClick('stop')}
      >
        <FloatButton
          icon={icons.getPosition}
          tooltip="获取坐标"
          onClick={() => onModeClick('start')}
        />
        <FloatButton
          icon={icons.clear}
          tooltip="清空"
          onClick={() => onModeClick('clear')}
        />
      </FloatButton.Group>
      <DraggableMarker.Group mapless={mapless} markers={mkrs} />
    </>
  );
};

export default PositionMkr;
